<script setup>
  import { ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { storeToRefs } from 'pinia'
  import slVehicleViolation from './components/vehicle-violation'
  import slVehicleBreakdown from './components/vehicle-breakdown'
  import slVehicleAccident from './components/vehicle-accident'
  import { useTaskStore } from '@/stores/task'
  import { truckRegApi } from '@/apis/task'

  const taskStore = useTaskStore()
  const { recordData } = storeToRefs(taskStore)

  // 出车时间
  onLoad((params) => {
    // 往仓库中存储id和发车时间
    recordData.value.id = params.transportTaskId
    recordData.value.startTime = params.actualDepartureTime
  })

  // 提交
  const onSubmitForm = async () => {
    // 1. 处理数据
    const { accidentImagesList, faultImagesList } = recordData.value
    recordData.value.accidentImagesList = accidentImagesList.map(({ url }) => {
      return { url }
    })
    recordData.value.faultImagesList = faultImagesList.map(({ url }) => {
      return { url }
    })

    // 2. 调用接口
    const { code } = await truckRegApi(recordData.value)
    if (code !== 200) return uni.utils.toast('回车登记失败~')

    // 清空仓库的数据
    taskStore.clearRecordData()

    // 3. 回去
    uni.reLaunch({
      url: '/pages/task/index',
    })
  }
</script>
<template>
  <view class="page-container">
    <scroll-view class="scroll-view" scroll-y>
      <view class="scroll-view-wrapper">
        <uni-list class="base-info">
          <!-- 出车时间 -->
          <uni-list-item
            title="出车时间"
            show-arrow
            :right-text="recordData.startTime"
          />
          <!-- 回车时间 -->
          <uni-list-item show-arrow title="回车时间">
            <template v-slot:footer>
              <uni-datetime-picker v-model="recordData.endTime">
                <view class="picker-value">{{
                  recordData.endTime || '请选择'
                }}</view>
              </uni-datetime-picker>
            </template>
          </uni-list-item>
        </uni-list>
        <!-- 交通违章 -->
        <sl-vehicle-violation></sl-vehicle-violation>
        <!-- 车辆故障 -->
        <sl-vehicle-breakdown></sl-vehicle-breakdown>
        <!-- 交通事故 -->
        <sl-vehicle-accident></sl-vehicle-accident>
      </view>
    </scroll-view>
    <view class="toolbar">
      <button class="button" @click="onSubmitForm">提交登记</button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
  @import './index.scss';
</style>
